import { listProductSpec, selectPurchaseProductAttrValueList } from '@/api/commercial';

// 商品查询参数构建器
export const buildProductQueryParams = ({
  categoryId = '',
  limit = 10,
  page = 1,
  productName = '',
  barCode = '',
  queryType = 'transfer', // transfer: 调拨查询, purchase: 采购查询
  extraParams = {},
  itemNumber = ''
}) => {
  const baseParams = {
    categoryId,
    limit,
    page,
    productName: productName || '',
  };

  if (barCode) {
    baseParams.barCode = barCode;
  }
  if (itemNumber) {
    baseParams.itemNumber = itemNumber;
  }

  if (queryType === 'transfer') {
    return {
      ...baseParams,
      transferOutStoreId: extraParams.transferOutStoreId,
      transferOutType: extraParams.transferOutType,
      transferInStoreId: extraParams.transferInStoreId,
      transferInType: extraParams.transferInType,
    };
  } else if (queryType === 'purchase') {
    return {
      ...baseParams,
      merId: extraParams.merId,
      merName: extraParams.merName,
      warehouseId: extraParams.warehouseId,
      warehouseName: extraParams.warehouseName,
    };
  }

  return baseParams;
};

// 商品查询方法
export const fetchProducts = async (params) => {
  const { queryType, ...queryParams } = params;
  console.log(queryType,48);
  const api = queryType === 'transfer' ? listProductSpec : selectPurchaseProductAttrValueList;
  
  try {
    const res = await api(queryParams);
    return {
      list: res.list || [],
      total: res.total || 0,
    };
  } catch (error) {
    console.error('查询商品失败:', error);
    throw error;
  }
};

// 商品库存检查
export const checkProductStock = (product, queryType = 'transfer') => {
  if (!product) return 0;
  // 只有调拨场景才校验库存
  if (queryType === 'transfer') {
    return product.transferOutStoreThenStock || 0;
  }
  // 采购场景不校验库存，返回最大安全整数
  return Number.MAX_SAFE_INTEGER;
};

// 商品查找方法
export const findExistingProduct = (productList, newProduct) => {
  if (!productList || !newProduct) return -1;
  return productList.findIndex(
    (item) => item.productAttrValueId === newProduct.productAttrValueId
  );
}; 